<?php
namespace app\controllers;

use app\commons\ApiResponse;
use app\models\ApiAuth;
use app\models\SysAuth;
use yii\filters\auth\HttpBearerAuth;
use yii\filters\Cors;
use yii\helpers\Json;

/**
 * Api请求响应基类
 * 定义相关的认证方式、速率等
 */
class ApiBaseController extends \yii\rest\Controller
{
//    public $modelClass;

    public function behaviors(): array
    {
        $behaviors = parent::behaviors();

        // 配置跨域
        $behaviors['corsFilter'] = [
            'class' => Cors::class,
            'cors' => [
                'Origin' => ['*'],
                'Access-Control-Request-Methods' => ['*'],
                'Access-Control-Request-Headers' => ['*'],
                'Access-Control-Allow-Credentials' => true,
            ]
        ];

        // 配置签名
        $behaviors['signAuth'] = [
            'class' => ApiAuth::class,
            'optional' => ['sign','get-version']
        ];

        // 配置认证
        $behaviors['bearerAuth'] = [
            'class' => HttpBearerAuth::class,
            'header'=>'token',
            'pattern'=> '/^(.*?)$/',
            'optional' => ['get-version','sign','get-token'],
        ];

        return $behaviors;
    }

    /**
     * @var ApiResponse
     */
    protected ApiResponse $_api;

    public function __construct($id, $module, $config = [])
    {
        parent::__construct($id, $module, $config);

        $this->_api = new ApiResponse();
    }

    public function actionSign()
    {
        $sign = new ApiAuth();
        $arr_get_params = $sign->getGetParams();
        $time = gmdate('U');
        $arr_get_params[$sign->timeParam] = $time;
        $arr_sign = [
            'params' => $arr_get_params,
            'raw' => $sign->getRaw(),
            'sign'=> $sign->getSign($arr_get_params),
            'time' => $time
        ];

        return $this->_api->success($arr_sign);
    }

    public function actionGetVersion()
    {
        $arr_version = [
            'version'=> \Yii::$app->params['version_info']['version'],
            'time' => \Yii::$app->params['version_info']['update_time']
        ];

        return $this->_api->success($arr_version);
    }

    public function actionDemo()
    {
        $demo = [
            'demo'=> 'demo',
        ];

        return $this->_api->success($demo);
    }

    public function actionGetToken()
    {
        $m_auth = new ApiAuth();
        $str_raw = \yii::$app->request->getRawBody();
        $req = Json::decode($str_raw);
        if(empty($req['app_code']) || empty($req['app_secret']) )
        {
            return $this->_api->error(406);
        }
        $app_code = $req['app_code'];
        $app_secret = $req['app_secret'];

        $m_auth = new SysAuth();
        $m_auth->app_code = $app_code;
        $m_auth->app_secret = $app_secret;

       return $this->_api->success($m_auth->getToken());

    }

}